package com.forezp.thinking.chapter18;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by forezp on 2017/12/8.
 */
public class Director {

    public static File[] local(File dir, final String regex) {
        return dir.listFiles(new FilenameFilter() {

            private Pattern pattern = Pattern.compile(regex);

            @Override
            public boolean accept(File dir, String name) {
                return pattern.matcher(new File(name).getName()).matches();
            }
        });

    }

    public static File[] local(String dir, final String regex) {
        return local(new File(dir), regex);

    }

    static class TreeInfo implements Iterable<File> {
        public List<File> dirs = new ArrayList<>();
        public List<File> files = new ArrayList<>();


        @Override
        public Iterator<File> iterator() {
            return files.iterator();
        }

        void addAll(TreeInfo other) {
            dirs.addAll(other.dirs);
            files.addAll(other.files);
        }
    }

    static TreeInfo recurseDirs(File startDir, String regex) {
        TreeInfo treeInfo = new TreeInfo();
        for (File item : startDir.listFiles()) {
            if (item.isDirectory()) {
                treeInfo.dirs.add(item);
                treeInfo.addAll(recurseDirs(item, regex));
            } else {
                if (item.getName().matches(regex)) {
                    treeInfo.files.add(item);
                }
            }

        }
        return treeInfo;
    }
}
